Skip to content

fix(artwork): keep the storage sweep from deleting artwork being re-cached - #5916

Open
Quick104 wants to merge 3 commits into
mainfrom
fix/artwork-sweep-reuse-race
Open

Quick104 wants to merge 3 commits into
mainfrom
fix/artwork-sweep-reuse-race

Conversation

@Quick104

@Quick104 Quick104 commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

Other clients: N/A (no client-visible change)

The artwork storage sweep could delete an artwork revision at the moment the image cache was reusing it, leaving a poster or backdrop pointing at objects that no longer exist until the artwork reconcile task noticed and reset the row.

The sweep checks an old object against the catalog, finds nothing referencing it, and deletes it a moment later. In between, the image cache can cache the same image again. Revisions are content-addressed, so the cache registers the same path with the revision tracker, sees the objects already stored, skips the upload, and publishes the path. The sweep's delete then removes the objects the catalog now points at. The revision GC doesn't have this race because it deletes while holding the revision's row lock, so the tracker waits for it. The sweep took no lock.

Found in review of #5914. The race is on main and was also flagged on the closed #5762.

Approach

The sweep now deletes each page under the same row locks the revision GC uses, in one transaction that only holds locks and always rolls back:

  • An untracked revision gets an uncommitted placeholder row, and a tracked one gets FOR UPDATE SKIP LOCKED. A re-cache arriving during the delete waits on that row and, once the objects are gone, uploads them again.
  • A revision whose row the tracker touched within the sweep's 24-hour age floor is left alone, because a cache pass may be about to publish it. So is a revision still inside the GC's grace period, and a row another transaction holds, such as the GC while it deletes. Both are counted in a new held stat and left for a later pass or the GC.

Handing orphans to the revision GC instead would write a row per orphan, and on a large bucket that is millions of rows. The GC also deletes only its manifest keys, not the keys the sweep listed.

One window remains, as it did before. Code that writes an already-stored path into the catalog without registering it with the tracker in the last 24 hours, between the sweep's reference check and its delete, can still lose that artwork. Every image-cache path registers first.

Validation

  • A new DB test drives the real sweep, revision tracker, and schema with a fake object store. Three cases: a re-cache that starts during the delete, one that registers between the reference check and the delete, and a row the GC holds. All three fail on main for the reason above and pass here.
  • internal/metadata with a test database, internal/taskmanager/tasks, make lint-changed, make lint-router-recovery, build, vet, gofmt, and go mod tidy -diff pass.
  • make test-go: failures only in internal/api/handlers, internal/backup, internal/ebookconvert, and internal/uploads, which fail the same way on main on the same host.
  • The sweep tests also pass on a merge of this branch with fix(artwork): sweep every prefix the artwork GC tracks #5914, which merges cleanly.
  • Not reproduced on a running server. The race needs a re-cache timed between two steps of one sweep page, so the test is the proof.

Evidence: https://evidence.siloserver.org/r/silo-server/artwork-sweep-recache-race/

Risks

  • While a page's storage delete runs, image-cache registrations for revisions on that page wait for it. The revision GC already does the same over larger batches. A page is at most 1,000 objects.
  • If a storage delete is cancelled or loses its connection after the request went out, the store may still carry it out after the transaction rolls back and a re-cache has reused the objects. The revision GC has the same gap. Closing it needs versioned deletes or a durable pending-delete state, which this change doesn't add.
  • Placeholder rows are never committed, so backups, the GC, and readers never see them.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or how I checked a change nobody sees.

Council review

Ran as a follow-up of #5914's review, with one member at medium effort.

Rounds: 1, reviewed dd2253e

Member Round 1
Sol (gpt-6.2-sol, medium) 7/10

Fixed: the test's re-cache now registers on its own connection pool, so a timeout can only mean it waited on the sweep's locks. Answered: a storage delete still in flight when its request is cancelled can land after the locks are released (listed under Risks). Sol returned its findings without posting a review. A Kody review after that round led to a 5 second bound on the rollback and the GC's grace-period check under the lock.

AI Disclosure

  • Harness: Claude Code in T3 Code
  • Tool(s): Claude Code
  • Model(s): claude-opus-5-5, claude-sonnet-5-5 (review subagents)
  • Involvement: Fully AI-generated, not yet human verified
  • Adversarial review: an Opus plan check removed a recheck of references inside the lock (it only moved the window) and deduplication. A medium multi-agent code review led to the held stat, a stricter wait assertion in the test, and a case for a row the GC holds. That case showed the placeholder insert also waits on an in-flight tracker upsert, and the comments now say so. The background round is under Council review.

🤖 Generated with Claude Code

Note

Fix artwork storage sweep to skip artwork being re-cached

The sweep could delete artwork from storage while it was being re-cached. Adds a deleteUnlessRecached helper in artwork_storage_sweep.go that coordinates with the database before deleting.

  • With a database pool, the helper runs in a transaction: it inserts candidate rows for untracked originals and locks eligible existing rows, and only deletes keys whose original was inserted or locked. Rows locked elsewhere or not yet past the age floor are left for a later sweep.
  • The transaction rolls back with a five-second timeout after the deletion attempt, including on error. Without a pool, deletion stays direct.
  • ArtworkStorageSweepStats gains a held count for doomed keys withheld from deletion, and partial-delete counts are now compared against the keys actually requested from storage rather than the full doomed list.

Macroscope summarized a428f51.

…ached

The storage sweep checked references and then deleted objects with no
coordination with the revision tracker. The image cache re-registers a
content-addressed revision, finds its objects already stored, skips the
upload, and publishes the path, so a sweep delete landing after that check
left the catalog pointing at missing artwork.

Delete under the same row locks the revision GC uses: hold a placeholder
row for an untracked revision and lock a tracked one, so a re-cache that
arrives meanwhile waits until the objects are gone and uploads them again.
Spare revisions the tracker touched within the sweep's age floor or that
the GC holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-triage silo-triage Bot added the size/L 200–499 added + deleted lines (all files); change volume, not priority. label Dec 6, 2026
@coderabbitai

coderabbitai Bot commented Dec 6, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Walkthrough

The artwork storage sweep now coordinates deletion with revision recaching through database candidate rows. It reports keys held from deletion and includes database tests for recache attempts and locked candidate rows.

Changes: Artwork sweep deletion

Layer / File(s) Summary
Gate sweep deletion on GC state
internal/metadata/artwork_storage_sweep.go, internal/metadata/artwork_storage_sweep_recache_db_test.go, scripts/ci/db-contracts.txt
SweepPrefix uses deleteUnlessRecached to select keys for deletion. The helper inserts missing candidate rows and locks eligible rows during storage deletion. ArtworkStorageSweepStats adds a Held count, and partial-delete checks use the number of requested keys. Database tests and the contract list cover recache attempts and locked candidate rows.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant SweepPrefix
  participant deleteUnlessRecached
  participant Database
  participant ArtworkStorage
  SweepPrefix->>deleteUnlessRecached: Submit doomed keys and age floor
  deleteUnlessRecached->>Database: Insert candidate rows and lock eligible rows
  deleteUnlessRecached->>ArtworkStorage: Delete keys with inserted or locked candidate rows
  deleteUnlessRecached->>Database: Roll back transaction and release locks
Loading

Suggested reviewers: rhainland

Merge Risk: Minimal · up to a428f

The artwork sweep now coordinates deletes with revision re-caching through database row locks, which closes the main window where a re-cache could reuse objects being deleted. No actionable merge-blocking issue was found. The author already documents the two narrow residual races.

Security architecture risk: Low · up to a428f

The change closes the normal sweep-versus-recache race without expanding what the sweep may delete. Waiting for a delete of the same revision is an intentional tradeoff, but a stalled storage call can now hold every eligible revision on that page and delay recaches that would otherwise proceed. A canceled S3 request also does not establish that storage stopped processing the delete.

Retained concerns

  • Minor · reliability · inferred: A slow or stalled storage delete now holds all eligible revision locks for that page and a shared database connection. Before this PR, that storage call did not hold revision locks. A recache must wait for deletion of its own revision, but the page-wide transaction can also delay a recache while storage is stalled on a different key or processing individual deletes. The five-second bound applies only once rollback starts; the sweep itself adds no deadline for holding the locks.

View findings in the submitted review

Security review details

Security Blast Radius

  • observed — The production task selects local/, tmdb/, and tvdb/ in the existing Assets store. It validates the checkpoint prefix against that list, and the sweep refuses an empty prefix. The changed delete path narrows the keys submitted from an eligible page; it does not add a bucket, credential, or request-controlled prefix.

Trust Boundaries and Controls

  • observed — Storage supplies the listed keys and timestamps, but the sweep makes the deletion decision. It skips missing or recent timestamps, consults catalog references, refuses anomalous pages it cannot account for, and now requires a revision lock or placeholder before submitting the remaining keys.

Public contracts

  • observed — The task's JSON result gains an additive held count. It counts eligible-for-consideration keys not submitted for deletion, including all doomed keys on a page if the database step fails; it is not an acknowledgment from storage. Partial-delete accounting compares the deleted count with the keys actually submitted.

Dependencies

  • observed — The production sweep now needs to insert and lock rows in the existing revision GC candidate table at deletion time, not merely read catalog and scheduling state. The transaction rolls back rather than persisting a GC candidate for every orphan.

Service and deployment topology

  • observed — Silo still registers the task against its application database pool and Assets store. The constructor rejects a missing pool or store, so the pool-less direct-delete branch is not used by this production wiring.

Data and control flow

  • observed — The sweep filters listed keys by age and catalog references before locking their original revisions. The image cache registers the original before checking or writing its variants. The sweep therefore honors a recent registration or makes that registration wait until its delete call returns.

Resilience and Maintainability Implications

  • inferred — After an acknowledged delete, a waiting cacher can upload any missing variants before returning a path. After an S3 request is dispatched and then canceled or loses its response, rollback releases database ownership without establishing whether storage has finished. A recache may still reuse keys affected by a late delete. This is a residual limit of the fix, not a new deletion exposure relative to the unlocked base. The sweep records progress where possible and revisits the namespace later; it does not repair a published pointer.
  • observed — Reconcile Artwork Cache is an explicit administrator recovery action, not an automatic follow-up to a failed sweep or a startup repair. When manually run, it checks storage, resets missing provider-backed artwork for separate backfill, and may clear a missing original that has no re-downloadable source. It does not restore the lost bytes.

Hardening Proposals

  • proposed — Bound how long a sweep may hold a batch of revision locks and reduce the number of revisions affected by a slow delete. If the design needs to guarantee safe reuse after an ambiguous remote result, use a deletion protocol that can distinguish an outstanding delete from a settled one; a shorter client timeout alone cannot establish that distinction.

Rollout and rollback

  • inferred — On upgraded sweep runners, PostgreSQL checks revision eligibility and lock ownership before each delete; failure to begin the transaction or obtain its results prevents submission of that page's deletes. The cluster advisory lock still selects one sweep runner, not a runner version. In a mixed-version rollout or after rollback to the merge-base behavior, an operator relying on the new guarantee must ensure that older sweep runners cannot run; they can still win the advisory lock and delete without the revision check.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the artwork storage sweep no longer deletes artwork that is being re-cached. The raw summary confirms the sweep now coordinates deletes with the revision tracker using…
Description check Passed The description explains the race between the artwork storage sweep and the image cache, the locking approach, the validation performed, the risks, and the remaining window. It is directly related to …
Linked Issues check Passed The only directly linked issue, #5762, is closed and completed. It is historical context only. Its requirement, adding mediux/ to artworkSweepPrefixes, does not apply to this pull request, which a…
Out of Scope Changes check Passed With no active linked issue, the scope reference is the pull request's stated concern: the artwork storage sweep deletes revisions that the image cache is re-caching. The raw summary shows changes tha…
Full details: Title check

Explanation

The title names the main change: the artwork storage sweep no longer deletes artwork that is being re-cached. The raw summary confirms the sweep now coordinates deletes with the revision tracker using row locks, so the title matches the changeset.

Full details: Description check

Explanation

The description explains the race between the artwork storage sweep and the image cache, the locking approach, the validation performed, the risks, and the remaining window. It is directly related to the changeset.

Full details: Linked Issues check

Explanation

The only directly linked issue, #5762, is closed and completed. It is historical context only. Its requirement, adding mediux/ to artworkSweepPrefixes, does not apply to this pull request, which addresses the sweep and re-cache race. No active linked-issue coding requirements remain, so no requirement is unmet. The pull request does not need to implement the #5762 prefix change.

Full details: Out of Scope Changes check

Explanation

With no active linked issue, the scope reference is the pull request's stated concern: the artwork storage sweep deletes revisions that the image cache is re-caching. The raw summary shows changes that all serve this concern: deleteUnlessRecached and the Held stat in internal/metadata/artwork_storage_sweep.go, the DB race tests in artwork_storage_sweep_recache_db_test.go, and the new test name in scripts/ci/db-contracts.txt. The partial-delete count fix is a direct consequence of withholding keys. No change shown is unrelated to the sweep race. This assessment relies on the whole-PR summary and did not read the full diff, so it does not verify every hunk.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@silo-kody

silo-kody Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-06T04:59:31.765566Z a428f51 New commits
🔒 Security Review ✅ Completed 2026-12-06T05:01:16.571135Z a428f51 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Dec 6, 2026
… test

A deadline on a shared pool could also mean the tracker never got a
connection, so the test could pass without the tracker waiting on the
sweep's locks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-kody

silo-kody Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@silo-kody

silo-kody Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments

Minor 1
  1. A slow or stalled storage delete now holds all eligible revision locks for that page and a shared database connection. Before this PR, that storage call did not hold revision locks. A recache must wait for deletion of its own revision, but the page-wide transaction can also delay a recache while storage is stalled on a different key or processing individual deletes. The five-second bound applies only once rollback starts; the sweep itself adds no deadline for holding the locks.
Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7ad3c710-40c0-4c8c-835c-4c78e71e5eae
Commits

Reviewing files that changed from the base of the PR and between b21744b and a428f51.

Files selected for processing: 3

  • internal/metadata/artwork_storage_sweep.go
  • internal/metadata/artwork_storage_sweep_recache_db_test.go
  • scripts/ci/db-contracts.txt

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@Quick104

Quick104 commented Dec 6, 2026

Copy link
Copy Markdown
Contributor Author

On CodeRabbit's actionable item (a slow or stalled storage delete now holds the page's revision locks and a database connection): this is intended, and it matches the revision GC. ArtworkRevisionGarbageCollector calls g.s3.Delete(ctx, keys) while it holds the candidate row locks in its transaction (internal/metadata/artwork_revision_gc.go). Holding the lock across the delete is what stops a re-cache from publishing a path while its objects are removed. A page is at most 1,000 keys, the sweep runs on one node at a time under its advisory lock, and the locks use SKIP LOCKED, so a held row only defers the GC. The S3 client has no per-request timeout on deletes, so a stalled storage call already holds the GC's locks the same way. Bounding storage calls would cover both and is a separate change.

🤖 Claude Code (claude-opus-5-5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/L 200–499 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant